<?php
/*
 *  微信接口
    华视文化2.0
    CopyRight 2014 All Rights Reserved
*/
header("content-type:text/html;charset=utf-8");
//引入基础函数类库
include_once("base-class.php");
//引入天气查询文件
//include_once("weather/weather.php");
//引入快递查询文件
//include_once("kuaidi/k_api.php");
//引入小黄鸡模块文件
//include_once("xiaohuangji/xiaohuangji.php");

define("TOKEN", "weixin");

$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
	$wechatObj->responseMsg();
}else{
    $wechatObj->valid();
}

class wechatCallbackapiTest
{
    public $mysql;
    public $mc;
	
    //构造函数
    function  __construct(){
	//新建mysql
	//$mysql = new SaeMysql();
	//新建Memcache类
	//$mc=memcache_init();
	echo "construct complete";
    }
	
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $this->logger("R ".$postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                case "location":
                    $result = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":
                    $result = $this->receiveVideo($postObj);
                    break;
                case "link":
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknow msg type: ".$RX_TYPE;
                    break;
            }
            $this->logger("T ".$result);
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

	//检测user的openid 参数是user的openid
	function check_user($fromUsername)
	{    
	    //$mysql = new SaeMysql();
		$roster_value=$mysql->getLine("select * from roster where roster_openid='$fromUsername'");
		//如果没有绑定
		if(!$roster_value)
		{
			return false;
		}
		//如果已经绑定（误取消重新关注员工）
		else
		{
			return $roster_value;        
		}

	}
	
	//快递函数
	public function kuaidi($s)
	{
		$t_o=explode("+",$s);
		$k_title=$t_o[0];
		//echo $k_title;
		$order_num=$t_o[1];
		include("kuaidi/k_api.php");
		foreach($k_api as $key=>$value)
		{
			if(strstr($key,$k_title))
			{
				$k_name=$k_api[$key];
				$jsons=file_get_contents("http://www.aikuaidi.cn/rest/?key=3fb5e7da487e4140ad2477034b98f911&order=$order_num&id=$k_name&ord=asc&show=json");
				$json=iconv("gb2312","UTF-8//IGNORE",$jsons);
				return json_decode($json);
			}
		}
	} 
	
    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
          case "subscribe":
			
			//如果是关注信息
				if(check_user($object->FromUserName))
				{
					//关注绑定的欢迎词
					 $content = "欢迎关注华视文化，您已经绑定了员工通讯录。\n请回复'YGCX'进行员工查询\n请回复'YGGX'进行员工更新\n退出请回复'EXIT'";
				}
				else{
				
					$content = "欢迎关注华视文化置家好人卡，您还没有绑定员工通讯录，请回复“BD”进行通讯录绑定";
			   }
                $content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
				
				
				
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
            case "SCAN":
                $content = "扫描场景 ".$object->EventKey;
                break;
            case "CLICK":
             //菜单点击事件推送
		   //用户点击了自定义的菜单，然后可以获取EventKey，就是在创建菜单时设置的菜单关键字
                switch ($object->EventKey)
                {
                    case "COMPANY":
                        $content = "华视文化提供互联网相关产品与服务。";
                        break;

					//获取菜单关键字
					case "置家365":
						$content = "欢迎关注华师文化\n您已经绑定了员工通讯录\n请回复'查询'进行查询\n请回复'更新'进行更新";
						break;
					case "置家366":
						$content = "您点击了置家366";
						break;
					case "置家367":
						$content = "您点击了置家367";
						break;
						
					case "置家E1":
						$content = "您点击了置家E1";
					    break;
					case "置家E2":
						$content = "您点击了置家E2";
					    break;
					case "置家E3":
						$content = "您点击了置家E3";
					    break;	
					case "华视文化":
						$content = "您点击了华视文化";
						break;
						
                    default:
                        $content = "点击菜单：".$object->EventKey;
                        break;

                }
                break;
            case "LOCATION":
                $content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }

    private function receiveText($object)
    {
        $keyword = trim($object->Content);
		
		//发送消息方ID
        $fromUsername = $object->FromUserName;
		
		//新建mysql
		$mysql = new SaeMysql();
		$mc=memcache_init();
		//从memcache获取用户上一次动作
         $last_do=$mc->get($fromUsername."_do");
        //从memcache获取用户上一次数据
         $last_data=$mc->get($fromUsername."_data");
		 
		/**  
		//快递 
		if(strpos($keyword,"+"))
		{
			$kd=$this->kuaidi($keyword);
			foreach($kd->data as $value)
			{
				$val.=$value->time."--".$value->content."  ||  ";
			}
			//$content[]="您查询是【{$kd->name}】，运单号【{$kd->order}】:  ".$val;
			$content = "您查询是".$kd->name."运单号：".$val;
			
		}else
		{
			$content="您输入信息没有找到或者您输入的不对";
			
		}
		**/
		 
        switch ($keyword)
        {
		
            case "文本":
                $content = "这是个文本消息".$last_data;
				
            break;
			
			
			case "小黄鸡":
			  $simsimi = new SimSimi();
			  $content = $simsimi->SimSimi($keyword);
			  $content = mb_convert_encoding($content, "gb2312", "UTF-8");
			  //$content = "输入了小黄鸡";
			
			break;
			
			case "jquery":
					$content[] = array("Title"=>"jquery", "Description"=>"jquery", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://1.huashiwhwx.sinaapp.com/jquery/index.html");
			break;
			
			
					
	//各种搜索类型
			//员工查询
			case "YGCX":
				
				$roster_value=$mysql->getLine("select * from roster");
				if($roster_value)
				{
					$content = "您要进行员工查询:\n按照工号查询请回复“GH”\n按照人名查询请回复“RM”";
				}else{
					$content = "没有接收到信息";
				}
			break;
			
			//按照工号查询
			case "GH":
			
			//用memcache保存部门搜索操作状态
                $mc->set($fromUsername."_do", "gh_search", 0, 600);
				$content = "请输入工号：";
			break;
				
			//接收到上一步是工号搜索状态，获取用户查询关键字
				
			
			//按照人名查询
			case "RM":
			
			break;
			
			case "YGGX":
			//进行员工更新
			break;
					
				//进行绑定操作
			case "BD":
				if(check_user($object->FromUserName))
                {
                    //提示已经绑定警告
                   $content = "你已经绑定账号，请不要重复操作！";
                }else{
				
					//用memcache保存这步操作，格式为名称、值、有效时间(单位秒)；
                   $mc->set($fromUsername."_do", "bd_0", 0, 600);
				}
			break;
		
			case "Exit":
				$content = "您已经进行了退出操作";
			break;
			
			
			case "图文":
            case "单图文":
                $content[] = array("Title"=>"单图文标题", "Description"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
				
				
                break;
            case "多图文":
                $content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
                $content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
                $content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
                break;
            case "音乐":
                $content = array("Title"=>"最炫民族风", "Description"=>"歌手：凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
                break;
				
			
	//输入大转盘
			case "大转盘":
				$content[] = array("Title"=>"大转盘", "Description"=>"大转盘", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://1.huashiwhwx.sinaapp.com/zhuanpan/index.htm");
				
				break;
	
	//刮刮卡
			case "刮刮卡":
				$content[] = array("Title"=>"刮刮卡", "Description"=>"刮刮卡", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://1.huashiwhwx.sinaapp.com/guaguaka/index.html");
				
			 break;
	//砸金蛋 
			case "砸金蛋":
				$content[] = array("Title"=>"砸金蛋", "Description"=>"砸金蛋", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://1.huashiwhwx.sinaapp.com/zajindan/index.html");
			break;
			 
	//天气查询
			case "天气查询":
			
			$getweather = new getweather();
            $content=$getweather->getw($keyword);
			
			break;
			
	//快递查询
			case "快递查询":
			
			//进行快递查询功能
			break;			
			
            default:
                $content = "当前时间：".date("Y-m-d H:i:s",time());
                break;
        }
		
		    switch($last_do){
			//接收到上一步是工号搜索状态，获取用户查询关键字
			case "gh_search":
			//判断是不是一个合法的员工号
			//查询数据库
            $roster_value=$mysql->getLine("select roster_id,roster_name,roster_number,roster_phone,roster_pic,roster_status 
                   							   from roster
                                                   where roster_number='$keyword'");
			$status = $roster_value['roster_number']?"在职":"离职";
			$content = "员工名称：".$roster_value['roster_name']."\n员工号：".$roster_value['roster_number']."\n员工状态".$status
			."\n手机号：".$roster_value['roster_phone'];
			
			//清空memcache动作
            $mc->delete($fromUsername."_do");
             //清空memcache数据
            $mc->delete($fromUsername."_data");
			 
			break;
			
		 }
		 
	//小黄鸡接口，表情回复
		if(preg_match("/\/::\-O|\/:xx|\/:\-\-b|\/::X|\/:no|\/::~|\/::@|\/::\(|\/::Q|\/::T|\/::d|\/::!|\/::L|\/::\-S|\/:,@@|\/::8|\/:,@!|\/:!!!|\/:dig|\/:pd|\/:pig|\/:fade|\/:break|\/:li|\/:bome|\/:kn|\/:shit/",$keyword)){

			$content = "不开心";

        }
		 
		if(preg_match("/\/::\)/",$keyword)){

			$content = "微笑";

        }
        if(preg_match("/\/:weak|\/:<@|\/:@>|\/:wipe|\/:@@|\/:bad|\/:shake/",$keyword)){

			$content = "不爽";

        }
        if(preg_match("/\/:moon|\/::Z|\/:\|\-\)|\/:bye|\/:beer|\/:\<W\>|\/::g/",$keyword)){

			$content = "再见";

        }
        if(preg_match("/\/:eat|\/:coffee/",$keyword)){

			$content = "吃饭";

        }
        if(preg_match("/\/:sun|\/:hiphot|\/:footb|\/:oo|\/:basketb|\/:jump|\/:circle|\/:skip|\/:<&|\/:&>/",$keyword)){

			$content = "运动";

        }
        if(preg_match("/\/:,@f|\/:heart|\/:showlove|\/:cake|\/:gift|\/:strong|\/::>|\/:gift|\/::B|\/:handclap|\/::\*|\/:rose|\/:kiss|\/:<L>|\/:love|\/:ok|\/:lvu|\/:jj|\/:@\)|\/:share|\/:hug/",$keyword)){

			$content = "喜欢";

        }
        if(preg_match("/\/::\+|\/:,@o|\/:X-\)|\/:v|\/:turn|\/:oY|\/:ladybug|\/:,@x|\/::,@|\/:8-\)|\/:#-0|\/:kotow|\/:\<O\>|\/:@x|\/:8\*|\/:P-\(|\/:>-\||\/:B-\)|\/:&-\(|\/:\?|\/::\||\/::<|\/::$|\/::-'\(|\/::-\||\/::P|\/::D|\/::O|\/:,@-D|\/:,@P/",$keyword)){

			$content = "夸张";

        }

	//小黄鸡接口结束
	
        if(is_array($content)){
            if (isset($content[0]['PicUrl'])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

    private function receiveImage($object)
    {
        $content = array("MediaId"=>$object->MediaId);
        $result = $this->transmitImage($object, $content);
        return $result;
    }

    private function receiveLocation($object)
    {
        $content = "你发送的是位置，纬度为：".$object->Location_X."；经度为：".$object->Location_Y."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    private function receiveVoice($object)
    {
        if (empty($object->Recognition)){
            $content = array("MediaId"=>$object->MediaId);
            $result = $this->transmitVoice($object, $content);
        }else{
            $content = "你刚才说的是：".$object->Recognition;
            $result = $this->transmitText($object, $content);
        }

        return $result;
    }

    private function receiveVideo($object)
    {
        $content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
        $result = $this->transmitVideo($object, $content);
        return $result;
    }

    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    private function transmitText($object, $content)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    private function transmitImage($object, $imageArray)
    {
        $itemTpl = "<Image>
    <MediaId><![CDATA[%s]]></MediaId>
</Image>";

        $item_str = sprintf($itemTpl, $imageArray['MediaId']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "<Voice>
    <MediaId><![CDATA[%s]]></MediaId>
</Voice>";

        $item_str = sprintf($itemTpl, $voiceArray['MediaId']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    private function transmitVideo($object, $videoArray)
    {
        $itemTpl = "<Video>
    <MediaId><![CDATA[%s]]></MediaId>
    <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
</Video>";

        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return;
        }
        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

    private function transmitMusic($object, $musicArray)
    {
        $itemTpl = "<Music>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
    <MusicUrl><![CDATA[%s]]></MusicUrl>
    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";

        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    private function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 10000;
            $log_filename = "log.xml";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }
}


?>